package org.jsbd.boss.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.jsbd.boss.annotation.SystemControllerLog;
import org.jsbd.boss.common.ConstantsCmp;
import org.jsbd.boss.common.ResponseUtils;
import org.jsbd.boss.common.redis.RedisClient;
import org.jsbd.boss.dao.IBrushApkConfigDao;
import org.jsbd.boss.dao.IBrushConfigDao;
import org.jsbd.boss.dao.IChannelApkConfigDAO;
import org.jsbd.boss.dao.IChannelApkLimitDAO;
import org.jsbd.boss.domian.ChannelApkConfigTimeModel;
import org.jsbd.boss.domian.channel.BrushApkConfig;
import org.jsbd.boss.domian.channel.BrushConfig;
import org.jsbd.boss.domian.channel.ChannelApkConfig;
import org.jsbd.boss.service.IBrushConfigService;
import org.jsbd.boss.service.IChannelLimitService;
import org.jsbd.boss.util.CacheKey;
import org.jsbd.boss.util.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/brushConfig")
public class BrushConfigController {
    public static final Logger LOGGER = LoggerFactory.getLogger(BrushConfigController.class);

    @Resource
    private IBrushApkConfigDao brushApkConfigDao;

    @Resource
    private IBrushConfigDao brushConfigDao;

    @Resource
    private RedisClient redisClient;

    @Resource
    private IChannelApkConfigDAO channelApkConfigDAO;

    @Resource
    private IChannelApkLimitDAO channelApkLimitDAO;

    @Resource
    private IBrushConfigService brushConfigService;

    @Resource
    private IChannelLimitService channelLimitService;

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String configList() {
        return "brushConfig/list";
    }

    // 基本配置查询展示接口
    @RequestMapping(value = "/list", params = "json")
    @ResponseBody
    public Map<String, Object> configPageList(BrushConfig config) {
        String brushName = config.getName();
        if (StringUtils.isNotBlank(brushName)) {
            String[] keys = brushName.trim().split(" ");
            List<String> keywords = new ArrayList<>();
            for (String keyword : keys) {
                keywords.add(keyword);
            }
            config.setKeywords(keywords);
        }
        config.setName(null);
        List<BrushConfig> list = brushConfigDao.selectList(config);
        String key = CacheKey.BRUSH_RECORD;
        for (BrushConfig config1 : list) {
            String fieldExecKey = DateUtil.getCurrentDateStr() + config1.getId() + "execTotal";
            Object execTotalObj = redisClient.evalHget(key, fieldExecKey);
            int execTotal = 0;
            if (execTotalObj != null) {
                execTotal = Integer.parseInt(execTotalObj.toString());
            }
            String realExecKey = DateUtil.getCurrentDateStr() + config1.getId() + "realExecTotal";
            Object realExecTotalObj = redisClient.evalHget(key, realExecKey);
            int realExecTotal = 0;
            if (realExecTotalObj != null) {
                realExecTotal = Integer.parseInt(realExecTotalObj.toString());
            }

            Integer isLimit = config1.getIsLimit();
            if (isLimit != null && isLimit == 1) {
                int timeLimit = channelLimitService.getTimeLimit(config1.getId().toString(), config1.getDayLimit());
                config1.setTaskNum(config1.getDayLimit() + "|" + timeLimit + "|" + execTotal + "|" + realExecTotal);
            } else {
                config1.setTaskNum(config1.getDayLimit() + "|" + config1.getDayLimit() + "|" + execTotal + "|" + realExecTotal);
            }


        }
        Integer total = brushConfigDao.countBrushConig(config);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("rows", list);
        map.put("total", total);
        return map;
    }

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String addConfig() {
        return "brushConfig/add";
    }

    @ResponseBody
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @SystemControllerLog(description = "brush新增")
    public void saveConfig(BrushConfig config, HttpServletResponse response) {
        Integer minTotal = config.getMinTotal();
        Integer maxTotal = config.getMaxTotal();
        Integer dayLimit = (int) (minTotal + (maxTotal - minTotal) * Math.random());
        config.setDayLimit(dayLimit);
        String url = config.getUrl();
        if (StringUtils.isNotBlank(url)) {
            url = url.trim().replace("\n", "").replace("\r", "");
            config.setUrl(url);
        }
        //版本号加1 同时记录连接
        long version = redisClient.incrementBy(CacheKey.BRUSH_CODE_KEY, 1);
        config.setCode(Integer.valueOf(version + ""));
        brushConfigDao.insertBrushConfig(config);

        BrushConfig temp = new BrushConfig();
        temp.setCode(Integer.parseInt(version + ""));
        BrushConfig apkConfig = brushConfigDao.selectConfig(temp);
        config.setBrushId(apkConfig.getId());
        brushConfigDao.insertBrushHistoryConfig(config);
        ResponseUtils.responseSuccess(response);
    }

    @RequestMapping(value = "{id}/configUpdate")
    public String configUpdate(BrushConfig config, Model model) {
        BrushConfig apkConfig = brushConfigDao.selectConfig(config);
        String url = apkConfig.getUrl();
        if (StringUtils.isNotBlank(url)) {
            url = url.trim().replace("\n", "").replace("\r", "");
            apkConfig.setUrl(url);
        }
        model.addAttribute("config", apkConfig);
        return "brushConfig/updateConfig";
    }

    @RequestMapping(value = "updateConfig", method = RequestMethod.POST)
    @SystemControllerLog(description = "更新配置")
    public void updateConfig(BrushConfig config, HttpServletResponse response) {
        try {
            boolean flag = this.brushConfigService.checkBrushUrl(config.getId(), config.getUrl());
            if (!flag) {
                ResponseUtils.responseCustomMsg(response, "链接填写错误");
            } else {
                Integer minTotal = config.getMinTotal();
                Integer maxTotal = config.getMaxTotal();
                Integer dayLimit = (int) (minTotal + (maxTotal - minTotal) * Math.random());
                config.setDayLimit(dayLimit);
                String url = config.getUrl();
                if (StringUtils.isNotBlank(url)) {
                    url = url.trim().replace("\n", "").replace("\r", "");
                    config.setUrl(url);
                }
                BrushConfig oldConfig = brushConfigDao.selectConfig(config);
                String oldConfigUrl = oldConfig.getUrl();
                config.setBrushId(config.getId());
                Integer code = config.getCode();
                if (code == null || code == 0 || !oldConfigUrl.equals(url)) {
                    //版本号加1 同时记录连接
                    long version = redisClient.incrementBy(CacheKey.BRUSH_CODE_KEY, 1);
                    config.setCode(Integer.valueOf(version + ""));
                    brushConfigDao.insertBrushHistoryConfig(config);
                }
                brushConfigDao.updateBrushConfig(config);
                brushConfigDao.updateBrushHistoryConfig(config);
                try {
                    ChannelApkConfigTimeModel model = new ChannelApkConfigTimeModel();
                    model.setMark(config.getId().toString());
                    model.setSpDayLimit(dayLimit);
                    model.setType(ConstantsCmp.add);
                    channelApkLimitDAO.updateTimeModel(model);
                } catch (Exception e) {
                    LOGGER.error("正态模型没有配置", e);
                }

                ResponseUtils.responseSuccess(response);
            }
        } catch (Exception e) {
            LOGGER.error("修改apk出错", e);
            ResponseUtils.responseFailure(response);
        }
    }

    @ResponseBody
    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    @SystemControllerLog(description = "brush删除")
    public void delete(BrushConfig config, HttpServletResponse response) {
        brushConfigDao.deleteBrushConfig(config);
        ResponseUtils.responseSuccess(response);
    }

    @RequestMapping(value = "saveApk", method = RequestMethod.POST)
    @SystemControllerLog(description = "saveApk保存")
    public void saveApk(BrushApkConfig config, @RequestBody List<Integer> apkIds, HttpServletResponse response) {
        Integer brushId = config.getBrushId();
        for (Integer apkId : apkIds) {
            BrushApkConfig config1 = new BrushApkConfig();
            config1.setBrushId(brushId);
            config1.setApkId(apkId);
            brushApkConfigDao.insertBrushApkConfig(config1);
        }
        ResponseUtils.responseSuccess(response);
    }


    @RequestMapping(value = "delApk", method = RequestMethod.POST)
    @SystemControllerLog(description = "delApk删除")
    public void delApk(BrushApkConfig config, @RequestBody List<Integer> apkIds, HttpServletResponse response) {
        Integer brushId = config.getBrushId();
        for (Integer apkId : apkIds) {
            BrushApkConfig config1 = new BrushApkConfig();
            config1.setBrushId(brushId);
            config1.setApkId(apkId);
            brushApkConfigDao.deleteBrushApkConfig(config1);
        }
        ResponseUtils.responseSuccess(response);
    }

    @RequestMapping(value = "{id}/apkList")
    public String apkList(BrushConfig brushConfig, Model model) {
        model.addAttribute("brushId", brushConfig.getId());
        model.addAttribute("baseId", brushConfig.getBaseId());
        return "brushConfig/addApkList";
    }

    @RequestMapping(value = "{brushId}/updateApkList", params = "json")
    @ResponseBody
    public Map<String, List<BrushApkConfig>> updateApkList(BrushApkConfig brushApkConfig, Model model) {
        Map<String, List<BrushApkConfig>> map = new HashMap<String, List<BrushApkConfig>>();

        String apkName = brushApkConfig.getApkName();
        ChannelApkConfig config = new ChannelApkConfig();
        config.setIsBrush(1);
        config.setBrushId(brushApkConfig.getBrushId());
        config.setBase(brushApkConfig.getBaseId());
        config.setIsDelete("0");
        if (StringUtils.isNotBlank(apkName)) {
            String[] keys = apkName.split(" ");
            List<String> keywords = new ArrayList<>();
            for (String keyword : keys) {
                keywords.add(keyword);
            }
            brushApkConfig.setKeywords(keywords);
            config.setKeywords(keywords);
        }

        List<BrushApkConfig> brushApkList = brushApkConfigDao.selectList(brushApkConfig);

        List<ChannelApkConfig> apkList = channelApkConfigDAO.selectApkInfos(config);
        List<BrushApkConfig> targetList = new ArrayList<>();
        for (ChannelApkConfig apk : apkList) {
            BrushApkConfig brushApkConfig1 = getBrushApkConfig(apk.getId(), brushApkList);
            if (brushApkConfig1 == null) {
                brushApkConfig1 = new BrushApkConfig();
                brushApkConfig1.setIsChecked(0);
                brushApkConfig1.setMark(apk.getMark());
                brushApkConfig1.setName(apk.getApkName());
                brushApkConfig1.setApkId(apk.getId());
            } else {
                brushApkConfig1.setIsChecked(1);
            }
            targetList.add(brushApkConfig1);
        }
        map.put("rows", targetList);
        return map;
    }

    private BrushApkConfig getBrushApkConfig(Integer apkId, List<BrushApkConfig> brushApkList) {
        for (BrushApkConfig brushApkConfig : brushApkList) {
            if (apkId.intValue() == brushApkConfig.getApkId().intValue()) {
                return brushApkConfig;
            }
        }
        return null;
    }

    @RequestMapping(value = "saveCheck", method = RequestMethod.POST)
    public void saveCheck(BrushApkConfig config, HttpServletResponse response) {
        brushConfigDao.saveCheck(config);
        ResponseUtils.responseSuccess(response);
    }
}
